package cn.ywang.spring.framework.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author BeatificWang
 * @date 2019/5/3 19:20
 */
public class View {

	private static final Pattern pattern = Pattern.compile("$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);


	public static final String DEFAULT_CONTENT_TYPE = "text/html;charset=utf-8";

	private File viewFile;

	public View(File viewFile) {
		this.viewFile = viewFile;
	}

	public void render(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
		StringBuffer sb = new StringBuffer();
		try {
			RandomAccessFile file = new RandomAccessFile(this.viewFile, "r");
			String line;
			while ((line = file.readLine()) != null) {
				line = new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
				Matcher matcher = this.matcher(line);
				while (matcher.find()) {
					for (int i = 1; i < matcher.groupCount(); i++) {
						//要把${}中间的这个字符串给取出来
						String paramName = matcher.group(i);
						Object paramValue = model.get(paramName);
						if (null == paramValue) {
							continue;
						}
						line = line.replaceAll("$\\{" + paramName + "}", paramValue.toString());
						line = new String(line.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
						matcher = this.matcher(line);
					}
				}
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setContentType(DEFAULT_CONTENT_TYPE);
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		try {
			response.getWriter().print(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Matcher matcher(String line) {
		Matcher matcher = pattern.matcher(line);
		return matcher;
	}
}
